package net.laenzlinger.decision.web;

import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.laenzlinger.decision.domain.RuleBase;
import net.laenzlinger.decision.service.KnowledgeBuilderException;
import net.laenzlinger.decision.service.RuleEngineService;
import net.laenzlinger.decision.service.container.Action;
import net.laenzlinger.decision.service.container.InputParameters;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/engine")
public class EngineController {

	@Autowired
	private RuleEngineService ruleEngineService;

	@RequestMapping(value = "/form/{id}", method = RequestMethod.GET)
	public String form(@PathVariable("id") Long id, Model model) {
		model.addAttribute("id", id);
		return "engine/form";
	}

	@RequestMapping(value = "/run/{id}", method = RequestMethod.GET)
	public String run(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response, Model model) {

		model.addAttribute("id", id);

		@SuppressWarnings("unchecked")
		Set<Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
		InputParameters params = new InputParameters();
		for (Entry<String, String[]> entry : entrySet) {
			params.put(entry.getKey(), entry.getValue()[0]);
		}

		try {
			RuleBase ruleBase = RuleBase.findRuleBase(id);
			List<Action> actions = ruleEngineService.execute(params, ruleBase);
			model.addAttribute("actions", actions);
			return "engine/actions";
		} catch (KnowledgeBuilderException e) {
			model.addAttribute("errors", e.getErrors());
			return "engine/errors";
		}

	}
}
